package com.skynet.backend.auth.sys.service.impl;

import com.skynet.backend.auth.common.util.Constant;
import com.skynet.backend.auth.sys.dao.SysMenuDao;
import com.skynet.backend.auth.sys.dao.SysUserDao;
import com.skynet.backend.auth.sys.entity.SysMenuEntity;
import com.skynet.backend.auth.sys.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Skynet
 * @date 2018年02月27日 13:06
 */
@Service("sysMenuService")
@Slf4j
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public List<SysMenuEntity> getUserMenuList(Long userId) {
        log.info("【查询用户菜单列表】userId:{}", userId);
        //系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN) {
            return getAllMenuList(null);
        }

        //用户菜单ID列表
        List<Long> menuIdList = sysMenuDao.queryMenuIdByUserId(userId);
        return getAllMenuList(menuIdList);
    }

    private List<SysMenuEntity> getAllMenuList(List<Long> menuIdList) {
        //查询根节点菜单列表
        List<SysMenuEntity> menuList = getMenuListByParentId(0L, menuIdList);

        //递归获取子节点菜单列表
        getSubMenuList(menuList, menuIdList);
        return menuList;
    }

    private List<SysMenuEntity> getSubMenuList(List<SysMenuEntity> menuList, List<Long> menuIdList) {
        List<SysMenuEntity> subMenuList = new ArrayList<SysMenuEntity>();

        for (SysMenuEntity menu : menuList) {
            if (menu.getMenuType() == Constant.MenuType.CATALOG.getValue()) {
                menu.setChildren(getSubMenuList(getMenuListByParentId(menu.getMenuId(), menuIdList), menuIdList));
            }
            subMenuList.add(menu);
        }
        return subMenuList;
    }

    @Override
    public List<SysMenuEntity> getMenuListByParentId(Long parentId, List<Long> menuIdList) {
        List<SysMenuEntity> menuList = getMenuListByParentId(parentId);
        if (menuIdList == null) {
            return menuList;
        }
        List<SysMenuEntity> userMenuList = new ArrayList<>();
        for (SysMenuEntity menu : menuList) {
            if (menuIdList.contains(menu.getMenuId())) {
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    @Override
    public List<SysMenuEntity> getMenuListByParentId(Long parentId) {
        return sysMenuDao.queryMenuListByParentId(parentId);
    }


}
